//
//  LeSideMenuViewController.m
//  LeSideMenuViewController
//
//  Created by CaiLei on 2/24/14.
//  Copyright (c) 2014 Le123. All rights reserved.
//

#import "LeSideMenuViewController.h"
@implementation UIViewController (LeSideMenuViewController)

- (LeSideMenuViewController *)sideMenuViewController
{
    UIViewController *iter = self.parentViewController;
    while (iter) {
        if ([iter isKindOfClass:[LeSideMenuViewController class]]) {
            return (LeSideMenuViewController *)iter;
        } else if (iter.parentViewController && iter.parentViewController != iter) {
            iter = iter.parentViewController;
        } else {
            iter = nil;
        }
    }
    return nil;
}

- (LeSideMenuViewController *)leSideMenuViewController
{
    UIViewController *iter = self.parentViewController;
    while (iter) {
        if ([iter isKindOfClass:[LeSideMenuViewController class]]) {
            return (LeSideMenuViewController *)iter;
        } else if (iter.parentViewController && iter.parentViewController != iter) {
            iter = iter.parentViewController;
        } else {
            iter = nil;
        }
    }
    return nil;
}

@end





@interface LeSideMenuViewController ()
@property (strong, readwrite, nonatomic) UIButton *contentButton;
@end

@implementation LeSideMenuViewController {
    CGPoint _orgCenter;
}

#pragma mark - getter / setter
- (void)setContentViewController:(UIViewController *)contentViewController
{
    if (!_contentViewController) {
        _contentViewController = contentViewController;
        return;
    }
    CGRect frame = _contentViewController.view.frame;
    CGAffineTransform transform = _contentViewController.view.transform;
    [self _reHideController:_contentViewController];
    _contentViewController = contentViewController;
    [self _reDisplayController:contentViewController frame:self.view.bounds];
    contentViewController.view.transform = transform;
    contentViewController.view.frame = frame;
}

- (void)setContentViewController:(UIViewController *)contentViewController animated:(BOOL)animated
{
    if (!animated) {
        [self setContentViewController:contentViewController];
    } else {
        //contentViewController.view.alpha = 0;
        contentViewController.view.frame = self.contentViewController.view.bounds;
        [self.contentViewController.view addSubview:contentViewController.view];
        [UIView animateWithDuration:self.animationDuration animations:^{
            //contentViewController.view.alpha = 1;
        } completion:^(BOOL finished) {
            [contentViewController.view removeFromSuperview];
            [self setContentViewController:contentViewController];
        }];
    }
}

- (void)setMenuViewController:(UIViewController *)menuViewController
{
    if (!_menuViewController) {
        _menuViewController = menuViewController;
        return;
    }
    [self _reHideController:_menuViewController];
    _menuViewController = menuViewController;
    [self _reDisplayController:menuViewController frame:self.view.frame];
    [self.view bringSubviewToFront:self.contentViewController.view];
}

#pragma mark - load / unload
- (id)initWithContentViewController:(UIViewController *)contentViewController menuViewController:(UIViewController *)menuViewController
{
    self = [self init];
    if (self) {
        _contentViewController = contentViewController;
        _menuViewController = menuViewController;
        
        _animationDuration = 0.35;
        _menuOffsetX = 180.f;
        _menuBounceX = 0.f;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _orgCenter = self.view.center;
	// Do any additional setup after loading the view.
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.contentButton = ({
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectNull];
        [button addTarget:self action:@selector(hideMenu) forControlEvents:UIControlEventTouchUpInside];
        button;
    });
    
    [self _reDisplayController:self.menuViewController frame:self.view.bounds];
    [self _reDisplayController:self.contentViewController frame:self.view.bounds];
    //self.menuViewController.view.alpha = 0.f;
    self.contentViewController.view.layer.shadowColor = [UIColor grayColor].CGColor;
    self.contentViewController.view.layer.shadowOffset  = CGSizeMake(-3, 0);
    self.contentViewController.view.layer.shadowRadius = 6;
    self.contentViewController.view.layer.shadowOpacity = 0.3;

    if (self.bInnerPan) {
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognized:)];
        panGestureRecognizer.delegate = self;
        [self.view addGestureRecognizer:panGestureRecognizer];
    }
    
    if (self.bOutterPan) {
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognized:)];
        panGestureRecognizer.delegate = self;
        [self.contentButton addGestureRecognizer:panGestureRecognizer];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - public API
- (void)showMenu {
    if (self.delegate && [self.delegate respondsToSelector:@selector(leSideMenuVCWillShowMenu:)]) {
        [self.delegate leSideMenuVCWillShowMenu:self];
    }
    [self.view.window endEditing:YES];
    [self _addContentButton];
    
    [UIView animateWithDuration:self.animationDuration animations:^{
        self.contentViewController.view.transform = CGAffineTransformIdentity;
        self.contentViewController.view.center = CGPointMake(_orgCenter.x + self.menuOffsetX, _orgCenter.y);
    } completion:^(BOOL finished) {
        self.bMenuVisible = YES;
    }];
}

- (void)hideMenu {
    [self.contentButton removeFromSuperview];
    
    [[UIApplication sharedApplication] beginIgnoringInteractionEvents];
    if (self.delegate && [self.delegate respondsToSelector:@selector(leSideMenuVCDidHideMenu:)]) {
        [self.delegate leSideMenuVCDidHideMenu:self];
    }

    [UIView animateWithDuration:self.animationDuration animations:^{
        self.contentViewController.view.transform = CGAffineTransformIdentity;
        self.contentViewController.view.center = _orgCenter;
    } completion:^(BOOL finished) {
        [[UIApplication sharedApplication] endIgnoringInteractionEvents];
        self.bMenuVisible = NO;
//        if (self.delegate && [self.delegate respondsToSelector:@selector(leSideMenuVCDidHideMenu:)]) {
//            [self.delegate leSideMenuVCDidHideMenu:self];
//        }
    }];
}

- (void)panGestureRecognized:(UIPanGestureRecognizer *)recognizer
{
    CGPoint point = [recognizer translationInView:self.view];
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.menuViewController.view.transform = CGAffineTransformIdentity;
        self.menuViewController.view.frame = self.view.bounds;
        [self _addContentButton];
        [self.view.window endEditing:YES];
    }
    
    if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) {
        //self.menuViewController.view.alpha = 1;
        if (!self.bMenuVisible) {
            point.x = MAX(0, point.x);
            point.x = MIN(self.menuOffsetX + self.menuBounceX, point.x);
        } else {
            point.x = MIN(point.x, 0);
            point.x = MAX(- self.menuOffsetX - self.menuBounceX, point.x);
        }
        
        self.contentViewController.view.transform = CGAffineTransformIdentity;
        self.contentViewController.view.transform = CGAffineTransformTranslate(self.contentViewController.view.transform, point.x, 0);
    }
    
    if (recognizer.state == UIGestureRecognizerStateEnded) {
        if ([recognizer velocityInView:self.view].x > 0) {
            [self showMenu];
        } else {
            [self hideMenu];
        }
    }
}

#pragma mark - private API
- (void)_reDisplayController:(UIViewController *)controller frame:(CGRect)frame
{
    [self addChildViewController:controller];
    controller.view.frame = frame;
    [self.view addSubview:controller.view];
    [controller didMoveToParentViewController:self];
}

- (void)_reHideController:(UIViewController *)controller
{
    [controller willMoveToParentViewController:nil];
    [controller.view removeFromSuperview];
    [controller removeFromParentViewController];
}

- (void)_addContentButton
{
    if (self.contentButton.superview)
        return;
    
    self.contentButton.autoresizingMask = UIViewAutoresizingNone;
    self.contentButton.frame = self.contentViewController.view.bounds;
    self.contentButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.contentViewController.view addSubview:self.contentButton];
}

- (BOOL)shouldAutorotate {
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

@end
